<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <el-card>
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="角色名称：">
                <el-input v-model="queryName" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="getRoleList">搜索</el-button>
                <el-button icon="Refresh" @click="resetRole">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin-top: 10px;">
        <div class="opreation">
            <el-button type="primary" icon="Plus" @click="dialogVisible = true;">添加角色</el-button>
            <el-button type="danger" icon="Delete" @click="removeMoreRole">批量删除</el-button>
        </div>
        <div class="table">
            <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" align="center"/>
                <el-table-column label="#" width="50" align="center">
                    <template #default="scope">{{ scope.$index+1 }}</template>
                </el-table-column>
                <el-table-column label="id" prop="id" width="100" align="center"></el-table-column>
                <el-table-column label="角色名称" prop="roleName" align="center"></el-table-column>
                <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
                <el-table-column label="更新时间" prop="updateTime" align="center"></el-table-column>
                <el-table-column label="操作" prop="" width="400" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="mini" icon="User" @click="fpPremisstion(scope.row.id)">分配权限</el-button>
                        <el-button type="warning" size="mini" icon="Edit" @click="editRole(scope.row.id)">编辑</el-button>
                        <el-popconfirm :title="`是否确认删除角色【${scope.row?.roleName||''}】?`" width="250px" icon="Delete" @confirm="confirmDelete(scope.row.id)">
                            <template #reference>
                                <el-button type="danger" size="mini" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 20, 30, 50, 100]"
                    :total
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>
    </el-card>
    <el-dialog 
        v-model="dialogVisible"
        :title="roleDto.id?'编辑角色':'新增角色'" 
        width="600"
        @closed="initReset"
    >
        <el-form
            ref="roleDtoRef"
            :model="roleDto"
            :rules="roleRules"
            label-width="auto"
            class="demo-ruleForm"
        >
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleDto.roleName" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAdd">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <el-drawer v-model="roleDrawer" direction="rtl">
        <template #header>
            <h2>分配权限</h2>
        </template>
        <template #default>
            <el-tree
                style="max-width: 600px"
                :data="menuData"
                show-checkbox
                node-key="id"
                :props="defaultProps"
                :default-expanded-keys="[1]"
                ref="menuTree"
            />
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelDrawer">取消</el-button>
                <el-button type="primary" @click="confirmDrawer">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
    import { ref, reactive, onMounted, nextTick } from "vue";
    import { ElMessage } from "element-plus";
    import roleApi from "@/api/acl/role";

    let queryName = ref('');
    let currentPage = ref(1);
    let pageSize = ref(10);
    let total = ref(0);
    let tableData = ref([]);
    let roleIds = ref([]);
    let dialogVisible = ref(false);
    let roleDto = reactive({
        id:'',
        roleName:'',
        createTime:'',
        updateTime:''
    });
    const roleRules = {
        roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
    }    
    const roleDtoRef = ref();
    let roleDrawer = ref(false);

    const defaultProps = {
        children: 'children',
        label: 'name',
    }
    let menuData = ref([]);
    let selectMenuIds = ref([]);
    let roleId = ref(0);
    const menuTree = ref();

    const handleSizeChange = (e:number) => {
        pageSize.value = e;
        getRoleList();
    }

    const handleCurrentChange = (e:number) => {
        currentPage.value = e;
        getRoleList();
    }
    const handleSelectionChange = (rows) => {
        roleIds.value = rows.map(item => item.id);
    }

    const resetRole = () => {
        queryName.value = '';
        currentPage.value = 1;
        pageSize.value = 10;
        tableData.value = [];
        total.value = 0;
        getRoleList();
    }

    const getRoleList = async () => {
        const res = await roleApi.getRoleListByName(currentPage.value, pageSize.value, queryName.value)
        if(res.code === 200){
            tableData.value = res.data.records;
            total.value = res.data.total;
        }else ElMessage.error(res.message);
    }

    const removeMoreRole = async () => {
        if(!roleIds.value?.length) return ElMessage.warning('请至少选择一条需要删除的角色');
        const res = await roleApi.removeRoleByIdList(roleIds.value);
        if(res.code === 200){
            ElMessage.success('删除成功');
            getRoleList();
        }else ElMessage.error(res.message);
    }

    const initReset = () => {
        dialogVisible.value = false;
        roleDto.id = '';
        roleDto.roleName = '';
        roleDtoRef.value.resetFields();
        nextTick(() => {
            roleDtoRef.value.clearValidate('roleName');
        });
    }

    const editRole = async (id:number) => {
        const res = await roleApi.getRoleById(id);
        if(res.code === 200){
            Object.assign(roleDto, res.data)
            dialogVisible.value = true;
        }else ElMessage.error(res.message);
    }

    const confirmAdd = () => {
        roleDtoRef.value.validate(async valid => {
            if(valid){
                if(roleDto.id) roleDto.updateTime = new Date().Format('yyyy-MM-dd hh:mm:ss');
                const res = await roleApi[roleDto.id?'updateRole':'addRole'](roleDto);
                if(res.code === 200){
                    ElMessage.success('添加成功');
                    initReset();
                    getRoleList();
                }else ElMessage.error(res.message);
            }
        });
    }

    const confirmDelete = async (id:number) => {
        const res = await roleApi.removeRoleById(id);
        if(res.code === 200){
            ElMessage.success('删除成功');
            getRoleList();
        }else ElMessage.error(res.message);
    }

    const fpPremisstion = async (id:number) => {
        roleDrawer.value = true;
        roleId.value = id;
        const res = await roleApi.getMenuByRoleId(id);
        if(res.code === 200){
            menuData.value = res.data;
            await getSelectMenuIds(res.data);
            console.log(selectMenuIds.value);
            menuTree.value?.setCheckedKeys(selectMenuIds.value);
        }else ElMessage.error(res.message);
    }

    const getSelectMenuIds = (data) => {
        for(let i = 0;i < data.length;i++){
            if(data[i].select) selectMenuIds.value.push(data[i].id);
            if(data[i].children?.length){
                getSelectMenuIds(data[i].children);
            }
        }
    }

    const cancelDrawer = () => {
        roleDrawer.value = false;
        roleId.value = 0;
        selectMenuIds.value = [];
        menuTree.value?.setCheckedKeys([]);
    }

    const confirmDrawer = async () => {
        if(menuTree.value?.getCheckedKeys().length){
            const res = await roleApi.setRoleMenuByRoleId({
                permissionIdList: menuTree.value?.getCheckedKeys(),
                roleId: roleId.value
            });
            if(res.code == 200){
                ElMessage.success('设置成功');
                roleDrawer.value = false;
                roleId.value = 0;
                selectMenuIds.value = [];
            }else ElMessage.error(res.message);
        }else ElMessage.warning('请选择菜单');
    }

    onMounted(() => {
        getRoleList();
    });
</script>

<style scoped lang="scss">
    :deep(.el-form-item){
        margin-bottom: 0;
    }

    .table {
        width: 100%;
        margin-top: 10px;
    }
    
    .pagination{
        display: flex;
        align-items: center;
        justify-content: center;       
        margin-top: 20px; 
    }
</style>